<template>
  <div class="bidding-library-container">
    <SidebarNav />
    <div class="main-content">
      <TopHeader />
      <div class="content-area">
        <h2 class="page-title">招标库</h2>
        <div class="operation-bar">
          <div class="search-box">
            <input type="text" placeholder="请输入关键词" v-model="searchKeyword" />
            <div class="search-icon-container">
              <img src="../assets/icons/搜索.svg" alt="搜索" class="search-icon" />
            </div>
          </div>
          <div class="action-buttons">
            <button class="batch-delete-btn" :class="{ 'active': batchMode }" @click="toggleBatchMode">
              {{ batchMode ? '批量删除' : '批量删除' }}
            </button>
            <button v-if="batchMode" class="cancel-btn" @click="cancelBatchMode">取消</button>
          </div>
        </div>
        
        <div class="table-container">
          <table class="bidding-table">
            <thead>
              <tr>
                <th v-if="batchMode" class="checkbox-column">
                  <input type="checkbox" v-model="selectAllCurrentPage" @change="toggleSelectAllCurrentPage" class="custom-checkbox" />
                </th>
                <th class="serial-column">序号</th>
                <th class="name-column">名称</th>
                <th class="time-column">创建时间</th>
                <th class="status-column">分析状态</th>
                <th class="operation-column">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in paginatedData" :key="item.id">
                <td v-if="batchMode" class="checkbox-column">
                  <input type="checkbox" v-model="item.selected" class="custom-checkbox" />
                </td>
                <td class="serial-column">{{ (currentPage - 1) * pageSize + index + 1 }}</td>
                <td class="name-column">{{ item.name }}</td>
                <td class="time-column">{{ item.createTime }}</td>
                <td class="status-column">
                  <div class="status-badge-container">
                    <span class="status-text" :class="{ 
                      'completed': item.status === '已完成',
                      'analyzing': item.status === '分析中'
                    }">
                      {{ item.status }}
                    </span>
                  </div>
                </td>
                <td class="operation-column">
                  <div class="operation-buttons">
                    <button class="view-btn" @click="viewItem(item)">查看</button>
                    <button class="delete-btn" @click="showDeleteConfirm(item)">删除</button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="pagination">
          <button class="prev-btn" :disabled="currentPage <= 1" @click="prevPage">&lt;</button>
          <div class="page-numbers">
            <span 
              v-for="page in displayedPages" 
              :key="page" 
              :class="{ 'active': currentPage === page }"
              @click="goToPage(page)"
            >
              {{ page }}
            </span>
          </div>
          <button class="next-btn" :disabled="currentPage >= totalPages" @click="nextPage">&gt;</button>
        </div>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog 
      :visible="deleteDialogVisible" 
      @cancel="deleteDialogVisible = false" 
      @confirm="confirmDelete" 
    />
    <tender-progress-assistant />
  </div>
</template>

<script>
import { ref, computed, reactive, watch } from 'vue';
import { useRouter } from 'vue-router';
import SidebarNav from '../components/Sidebar.vue';
import TopHeader from '../components/TopHeader.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import TenderProgressAssistant from '@/components/TenderProgressAssistant.vue';
import { ElMessage } from 'element-plus';

export default {
  name: 'BiddingLibrary',
  components: {
    SidebarNav,
    TopHeader,
    DeleteConfirmDialog,
    TenderProgressAssistant,
  },
  setup() {
    const router = useRouter();

    // 模拟数据
    const biddingData = reactive([
      { 
        id: 1, 
        name: '(定稿) 鲁抗医药SS-10-2项目、SS-16项目变压器采购 (1)', 
        createTime: '2025-06-23 16:51:23', 
        status: '已完成',
        selected: false
      },
      { 
        id: 2, 
        name: '(招标文件)国家电力投资集团有限公司物资装备分公司二〇二四年度第一批总包送物资电商化采购（箱变、开关柜、元切补偿、源母联架、敞侧母架）', 
        createTime: '2025-06-23 16:51:23', 
        status: '分析中',
        selected: false
      },
      { 
        id: 3, 
        name: '(招标文件)日用变压器、单板配电变压器、起重机变压器及其体及配套生产设备 (1)', 
        createTime: '2025-06-23 16:51:23', 
        status: '分析中',
        selected: false
      },
      { 
        id: 4, 
        name: '01-招标文件—浙江山鹰77万吨项目自干式变压器采购项目', 
        createTime: '2025-06-23 16:51:23', 
        status: '已完成',
        selected: false
      },
      { 
        id: 5, 
        name: '1_招标文件BTXCLZB-204-004---宝珠新材料干式变压器招标', 
        createTime: '2025-06-23 16:51:23', 
        status: '已完成',
        selected: false
      },
      { 
        id: 6, 
        name: '招标文件示例6', 
        createTime: '2025-06-23 16:51:23', 
        status: '已完成',
        selected: false
      },
      { 
        id: 7, 
        name: '招标文件示例7', 
        createTime: '2025-06-23 16:51:23', 
        status: '分析中',
        selected: false
      },
      { 
        id: 8, 
        name: '招标文件示例8', 
        createTime: '2025-06-23 16:51:23', 
        status: '已完成',
        selected: false
      }
    ]);

    // 分页设置
    const currentPage = ref(1);
    const pageSize = ref(5);
    
    // 搜索关键词
    const searchKeyword = ref('');
    
    // 批量删除模式
    const batchMode = ref(false);
    const selectAllCurrentPage = ref(false);
    
    // 删除确认对话框
    const deleteDialogVisible = ref(false);
    const itemToDelete = ref(null);
    
    // 根据关键词过滤数据
    const filteredData = computed(() => {
      if (!searchKeyword.value) return biddingData;
      return biddingData.filter(item => 
        item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      );
    });
    
    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(filteredData.value.length / pageSize.value);
    });
    
    // 当前页的数据
    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredData.value.slice(start, end);
    });
    
    // 显示的页码范围
    const displayedPages = computed(() => {
      const pages = [];
      const maxVisiblePages = 5;
      
      let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
      let endPage = Math.min(totalPages.value, startPage + maxVisiblePages - 1);
      
      if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
      }
      
      for (let i = startPage; i <= endPage; i++) {
        pages.push(i);
      }
      
      return pages;
    });
    
    // 监听分页变化，重置当前页的全选状态
    watch(currentPage, () => {
      updateSelectAllCurrentPageState();
    });
    
    // 监听分页数据变化，更新全选状态
    watch(paginatedData, () => {
      updateSelectAllCurrentPageState();
    }, { deep: true });
    
    // 更新当前页全选状态
    const updateSelectAllCurrentPageState = () => {
      selectAllCurrentPage.value = paginatedData.value.length > 0 && 
        paginatedData.value.every(item => item.selected);
    };
    
    // 切换批量删除模式
    const toggleBatchMode = () => {
      if (batchMode.value && hasSelectedItems.value) {
        // 如果已经在批量模式并且有选中项，则显示删除确认
        deleteDialogVisible.value = true;
      } else if (batchMode.value) {
        // 如果在批量模式但没有选中项，提示用户
        ElMessage({
          message: '请选择要删除的文件',
          type: 'warning'
        });
      } else {
        // 否则切换批量模式
        batchMode.value = !batchMode.value;
        selectAllCurrentPage.value = false;
        biddingData.forEach(item => {
          item.selected = false;
        });
      }
    };
    
    // 取消批量模式
    const cancelBatchMode = () => {
      batchMode.value = false;
      selectAllCurrentPage.value = false;
      biddingData.forEach(item => {
        item.selected = false;
      });
    };
    
    // 全选/取消全选当前页
    const toggleSelectAllCurrentPage = () => {
      paginatedData.value.forEach(item => {
        item.selected = selectAllCurrentPage.value;
      });
    };
    
    // 是否有选中项
    const hasSelectedItems = computed(() => {
      return biddingData.some(item => item.selected);
    });
    
    // 显示删除确认对话框
    const showDeleteConfirm = (item) => {
      itemToDelete.value = item;
      deleteDialogVisible.value = true;
    };
    
    // 确认删除
    const confirmDelete = () => {
      if (batchMode.value && hasSelectedItems.value) {
        // 批量删除
        const newData = biddingData.filter(item => !item.selected);
        biddingData.length = 0;
        biddingData.push(...newData);
        
        // 批量删除后退出批量删除模式
        cancelBatchMode();
      } else if (itemToDelete.value) {
        // 单个删除
        const index = biddingData.findIndex(item => item.id === itemToDelete.value.id);
        if (index !== -1) {
          biddingData.splice(index, 1);
        }
      }
      
      // 重置
      deleteDialogVisible.value = false;
      itemToDelete.value = null;
      
      // 如果当前页没有数据了，回到上一页
      if (paginatedData.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
      }
    };
    
    // 查看项目
    const viewItem = (item) => {
      // 以后可能会根据 item.id 跳转到不同的详情页
      console.log('查看项目:', item.id);
      router.push('/aichat'); // 跳转到 AI 对话页面
    };
    
    // 分页方法
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };
    
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };
    
    const goToPage = (page) => {
      currentPage.value = page;
    };
    
    return {
      biddingData,
      searchKeyword,
      currentPage,
      pageSize,
      totalPages,
      paginatedData,
      displayedPages,
      batchMode,
      selectAllCurrentPage,
      deleteDialogVisible,
      prevPage,
      nextPage,
      goToPage,
      toggleBatchMode,
      cancelBatchMode,
      toggleSelectAllCurrentPage,
      showDeleteConfirm,
      confirmDelete,
      viewItem,
      hasSelectedItems
    };
  }
};
</script>

<style scoped>
.bidding-library-container {
  display: flex;
  min-height: 100vh;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.content-area {
  flex: 1;
  padding: 20px 30px;
}

.page-title {
  color: #515151;
  font-size: 24px;
  margin-bottom: 35px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 35px;
}

.search-box {
  position: relative;
  width: 300px;
  display: flex;
  align-items: center;
}

.search-box input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  outline: none;
  font-size: 14px;
  background-color: #ECF0F1;
}

.search-icon-container {
  position: absolute;
  right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-icon {
  width: 20px;
  height: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.batch-delete-btn, .cancel-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
}

.batch-delete-btn {
  background-color: #9A9A9A;
  color: white;
}

.batch-delete-btn.active {
  background-color: #DB5A6B;
}

.cancel-btn {
  background-color: #9A9A9A;
  color: white;
}

.table-container {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
  margin-bottom: 20px;
}

.bidding-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.bidding-table th, .bidding-table td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bidding-table th {
  background-color: #3498DB;
  color: white;
  font-weight: 600;
}

.checkbox-column {
  width: 60px;
  text-align: center;
}

.serial-column {
  width: 80px;
}

.name-column {
  width: 40%;
}

.time-column {
  width: 15%;
}

.status-column {
  width: 15%;
}

.operation-column {
  width: 15%;
  padding-right: 20px;
}

.custom-checkbox {
  width: 20px;
  height: 20px;
  accent-color: #1684FC;
  cursor: pointer;
}

.status-badge-container {
  display: flex;
  justify-content: flex-start;
}

.status-text {
  display: inline-block;
  font-size: 14px;
  white-space: nowrap;
  font-weight: 500;
}

.status-text.completed {
  color: #81B337;
}

.status-text.analyzing {
  color: #DB5A6B;
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.view-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 13px;
  color: white;
  white-space: nowrap;
  min-width: 65px;
  text-align: center;
}

.view-btn {
  background-color: #71D9DA;
}

.delete-btn {
  background-color: #DB5A6B;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.prev-btn, .next-btn {
  padding: 5px 10px;
  border: 1px solid #dcdfe6;
  background-color: white;
  cursor: pointer;
  border-radius: 5px;
}

.prev-btn:disabled, .next-btn:disabled {
  cursor: not-allowed;
  color: #c0c4cc;
}

.page-numbers {
  display: flex;
  margin: 0 10px;
}

.page-numbers span {
  padding: 5px 10px;
  margin: 0 5px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  border-radius: 5px;
}

.page-numbers span.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}
</style> 